package com.evil.application.pojo.dto.es;

import co.elastic.clients.elasticsearch._types.Script;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import com.evil.application.enums.reporting.SummaryTypeEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * @author liyang
 * @date 2023-08-08 21:10
 */
@Data
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = true)
public class AggSummary extends Agg {

    private Summary summary;

    public AggSummary(String title) {
        super(title);
    }

    @Override
    public Aggregation.Builder.ContainerBuilder toAggregation() {
        String valueField = this.summary.valueField;
        Integer summaryType = this.summary.summaryType;
        Integer decimal = this.summary.decimal;
        String scriptFormat = "try{ if(doc['%s'].size()>0 ){ return Double.parseDouble(doc['%s'].value);} else{ return 0} } catch(Exception e) { return 0;}";
        String scriptStr = String.format(scriptFormat, valueField, valueField);
        Script script = Script.of(e -> e.inline(esi -> esi.source(scriptStr)));
        StringBuilder format = new StringBuilder();
        if (decimal != null && decimal > 0) {
            format.append(".");
            for (int i = 0, l = decimal; i < l; i++) {
                format.append("0");
            }
        }

        Aggregation.Builder.ContainerBuilder value;
        SummaryTypeEnum summaryTypeEnum = SummaryTypeEnum.findById(summaryType);
        value = switch (summaryTypeEnum) {
            case COUNT -> new Aggregation.Builder().valueCount(e -> e.field(valueField));
            case SUM -> new Aggregation.Builder().sum(e -> e.script(script).format(format.toString()));
            case AVERAGE -> new Aggregation.Builder().avg(e -> e.script(script).format(format.toString()));
            case MAX -> new Aggregation.Builder().max(e -> e.script(script).format(format.toString()));
            case MIN -> new Aggregation.Builder().min(e -> e.script(script).format(format.toString()));
            case NEWEST_DATA -> null;
            case OLDEST_DATA -> null;
            //case FORMULA -> new Aggregation.Builder()
            //        .scriptedMetric(b -> b
            //                .initScript(s -> s
            //                        .inline(e -> e
            //                                .lang(ScriptLanguage.Java)
            //                                .options(new HashMap<>())
            //                                .source("")
            //                        )
            //                )
            //        );
            default -> new Aggregation.Builder().missing(e -> e.field(valueField));
        };
        return value;
    }

    @Data
    @AllArgsConstructor
    public static class Summary {
        private String valueField;
        private Integer summaryType;
        private Integer decimal;
    }
}
